import me.tuyou.bean.MyInterface;
import me.tuyou.bean.MyInterfaceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description
 * @Author tuyou_cd
 * @Date 2020/6/1 18:48
 */
public class ProxyFactory implements InvocationHandler {

    private MyInterface source;

    public ProxyFactory(MyInterface source) {
        this.source = source;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        Object invoke = method.invoke(source, args);
        System.out.println("after");
        return invoke;
    }

    public MyInterface getProxy() {
        return (MyInterface) Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), source.getClass().getInterfaces(), this);
    }

    public static void main(String[] args) {

        MyInterface myInterface = new MyInterfaceImpl();
        ProxyFactory proxyFactory = new ProxyFactory(myInterface);
        MyInterface proxyObj = proxyFactory.getProxy();

        proxyObj.say("tuyou");
    }
}
